/**
 * 
 */
package com.wgo.precise.client.ui.view.editor.history;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;


import com.wgo.bpot.domain.common.CommandHistory;
import com.wgo.precise.client.ui.controller.ModelStatus;
import com.wgo.precise.client.ui.controller.RequirementPlugin;
import com.wgo.precise.client.ui.controller.listeners.SessionStatusListener;
import com.wgo.precise.client.ui.model.ClientModelItem;
import com.wgo.precise.client.ui.view.editor.AbstractFormPage;

/**
 * @author Petter L. H. Eide
 *
 */
public class HistoryFormPage extends AbstractFormPage implements SessionStatusListener {

	public final static String PAGE_ID = "modelHistory" ;
	public final static String PAGE_TITLE = "History" ;
	private TableViewer tableViewer = null ;
	
	public HistoryFormPage(FormEditor editor) {
		super(editor, PAGE_ID, PAGE_TITLE);
	}

	@Override
	protected void createFormContent(IManagedForm managedForm) {
		FormToolkit toolkit = managedForm.getToolkit(); 
		ScrolledForm form = managedForm.getForm();
		
		
//		Composite body = toolkit.createComposite(form);
		Composite body = form.getBody();
		
		GridLayout layout = new GridLayout();
		layout.marginWidth = 10;
		layout.marginHeight = 10;

		body.setLayout(layout);
		
		GridData gd = new GridData();

//		button = toolkit.createButton(body, "Refresh from server", SWT.WRAP ) ;
//		gd = new GridData ( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_END );
//		gd.widthHint = 10 ;
//		button.setLayoutData ( gd ) ;
//		button.addSelectionListener(
//				new SelectionListener()
//				{
//					/* (non-Javadoc)
//					 * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
//					 */
//					public void widgetDefaultSelected(SelectionEvent e) {
//					}
//					/* (non-Javadoc)
//					 * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
//					 */
//					public void widgetSelected(SelectionEvent e) {
//						if (e.widget == button) {
//							refresh();
//					    }
//					}
//				});
		
		form.setText("History");
		form.setToolTipText("List of previously changes to the target object.");

		final Table table = toolkit.createTable(body, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION );
		TableLayout tlayout = new TableLayout() ;

		TableColumn column = null;
		int tableWithHint = 10;
		for ( HistoryColumnProperties prop : HistoryColumnProperties.values()) {
			column = new TableColumn (table, SWT.LEFT, prop.ordinal());
			column.setText(prop.name());
			tlayout.addColumnData(new ColumnPixelData(prop.width()));
			tableWithHint += prop.width() ;
			column.addSelectionListener(new SelectionAdapter() {
				/**
				 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
				 */
				@Override
				public void widgetSelected(SelectionEvent e) {
					TableColumn sortColumn = table.getSortColumn();
					TableColumn currentColumn = (TableColumn) e.widget;
					int dir = table.getSortDirection();
					if (sortColumn == currentColumn) {
						dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
					} else {
						table.setSortColumn(currentColumn);
						dir = SWT.UP;
					}

//					// sort the data based on column and direction
//					final int index = HistoryColumnProperties.valueOf(currentColumn.getText()).ordinal();//currentColumn == column1 ? 0 : 1;
					final HistoryColumnProperties property = HistoryColumnProperties.valueOf(currentColumn.getText());
					final int direction = dir;
					Collections.sort((List<CommandHistory>)tableViewer.getInput(), new Comparator<CommandHistory>() {
						public int compare(CommandHistory arg0, CommandHistory arg1) {
							int inverse = 1 ;
							if (SWT.DOWN == direction){
								inverse = -1 ;
							}
							return property.getValue(arg0).compareTo(property.getValue(arg1)) * inverse;
//							int[] a = (int[]) arg0;
//							int[] b = (int[]) arg1;
//							if (a[index] == b[index]) return 0;
//							if (direction == SWT.UP) {
//								return a[index] < b[index] ? -1 : 1;
//							}
//							return a[index] < b[index] ? 1 : -1;
//							return 0;
						}
					});
					// update data displayed in table
					table.setSortDirection(dir);
					//tableViewer.refresh(null,true);
					table.clearAll();
					tableViewer.refresh(null,true);
				}
			});
		}
		table.setSortColumn(table.getColumn(0));
		table.setSortDirection(SWT.UP);
		
		gd = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING );
		gd.minimumWidth = tableWithHint ;
		gd.minimumHeight = 60 ;
		table.setLayoutData(gd);

		table.setLayout(tlayout);
		
        table.setLinesVisible(true);
        table.setHeaderVisible(true);

		tableViewer = new TableViewer(table);
		tableViewer.setContentProvider(new HistoryTableContentViewer());
		tableViewer.setColumnProperties(HistoryColumnProperties.names());
		tableViewer.setLabelProvider(new HistoryTableLabelProvider());
		tableViewer.setInput( ((ClientModelItem)getModelItem()).getHistory() );
		
//		RequirementPlugin.getInstance().getPreciseSubject().addListener(SessionStatusListener.class, this);

	}
	
	@Override
	public void dispose() {
		super.dispose();
//		RequirementPlugin.getInstance().getPreciseSubject().removeListener(SessionStatusListener.class, this);
		//text.dispose() ;
//		text = null;
		tableViewer = null ;
	}
	
	@Override
	public void setFocus() {
		tableViewer.getControl().setFocus();
	}

	@Override
	public synchronized void refresh() {
			RequirementPlugin.log(new ModelStatus (IStatus.INFO , HistoryFormPage.class.getSimpleName() + " update.."  ) );
			tableViewer.setInput(((ClientModelItem)getModelItem()).getHistory());
			tableViewer.refresh(true);
			getManagedForm().reflow(true);
	}

	/**
	 * @see com.wgo.precise.client.ui.controller.listeners.SessionStatusListener#onSave()
	 */
	public void onSave() {
		if (isActive()) {
			refresh();
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.forms.editor.FormPage#setActive(boolean)
	 */
	@Override
	public void setActive(boolean active) {
		if (active) {
			refresh();
		}
		super.setActive(active);
	}

	
	
}